"use client";

import React, { useState, ChangeEvent, useEffect } from "react";
import { useLanguage } from "~/lib/LanguageContext";
import { useRouter } from "next/navigation";
import { Button } from "./ui/button";
import OutputTypeSelector, { OutputType } from "./output-type-selector";

interface HeroProps {
  onGenerate?: (url: string, username: string, repo: string) => void;
  onChange?: (value: string) => void;
}

// 示例仓库数据
const examples = [
  { name: "FastAPI", url: "https://github.com/tiangolo/fastapi" },
  { name: "Next.js", url: "https://github.com/vercel/next.js" },
  { name: "React", url: "https://github.com/facebook/react" },
  { name: "TypeScript", url: "https://github.com/microsoft/TypeScript" }
];

interface ParsedUrl {
  username: string;
  repo: string;
  url: string;
}

const Hero = ({ onGenerate, onChange }: HeroProps) => {
  const { t, language } = useLanguage();
  const router = useRouter();
  const [repoInput, setRepoInput] = useState("");
  const [outputType, setOutputType] = useState<OutputType>("diagram");
  
  // 判断是否为中文界面
  const isChinese = language === 'zh';
  
  // 记录组件初始化
  console.log("【Hero组件初始化】使用的输出类型:", outputType);
  
  // 从localStorage恢复上次选择的输出类型
  useEffect(() => {
    if (typeof window !== 'undefined') {
      const savedType = localStorage.getItem('current_document_type') as OutputType | null;
      // 检查是否是有效的输出类型
      if (savedType && ["diagram", "overview-doc", "detailed-doc", "database-doc", "api-doc", "deployment-doc"].includes(savedType)) {
        console.log(`【Hero组件】从localStorage恢复输出类型: ${savedType}`);
        setOutputType(savedType);
      }
    }
  }, []);
  
  // 处理输出类型变更
  const handleOutputTypeChange = (newType: OutputType) => {
    console.log(`【Hero组件】输出类型变更: 从 ${outputType} 到 ${newType}`);
    setOutputType(newType);
    
    // 保存到localStorage以便在其他页面使用
    if (typeof window !== 'undefined') {
      localStorage.setItem('current_document_type', newType);
    }
  };
  
  // 解析GitHub URL
  const parseGitHubUrl = (input: string): ParsedUrl | null => {
    try {
      const url = input.trim();
      
      // 尝试各种可能的URL格式
      const githubUrlRegex = /(?:https?:\/\/)?(?:www\.)?github\.com\/([^/]+)\/([^/]+)/;
      const codeMarinerUrlRegex = /(?:https?:\/\/)?(?:www\.)?codemariner\.com\/([^/]+)\/([^/]+)/;
      
      let match = url.match(githubUrlRegex);
      if (!match) {
        match = url.match(codeMarinerUrlRegex);
      }
      
      if (match && match[1] && match[2]) {
        const username = match[1];
        const repoPath = match[2];
        const repo = repoPath.split('/')[0]; // 移除额外路径
        
        // 确保所有值都是有效的字符串
        if (username && repo) {
          return {
            username,
            repo,
            url: `https://github.com/${username}/${repo}`
          };
        }
      }
      
      return null;
    } catch (error) {
      console.error("Error parsing URL:", error);
      return null;
    }
  };
  
  // 处理生成图表
  const handleGenerate = (event: React.FormEvent) => {
    event.preventDefault();
    
    // 解析GitHub URL格式
    const parsedUrl = parseGitHubUrl(repoInput);
    if (!parsedUrl) return;
    
    const { username, repo, url } = parsedUrl;
    
    // 如果提供了外部回调则调用
    if (onGenerate) {
      onGenerate(url, username, repo);
    } else {
      // 默认导航行为 - 根据输出类型选择不同路径
      console.log("【Hero组件】准备导航，选择的输出类型:", outputType);
      
      // 设置全局模式标记，确保使用正确的钩子
      if (typeof window !== 'undefined') {
        if (outputType === 'diagram') {
          // 设置图表模式标记
          window._isDiagramMode = true;
          // 移除文档模式标记（如果有）
          if (window._isDocumentMode) {
            delete window._isDocumentMode;
          }
          console.log("【Hero组件】设置图表模式标记，移除文档模式标记");
        } else {
          // 设置文档模式标记
          window._isDocumentMode = true;
          // 移除图表模式标记（如果有）
          if (window._isDiagramMode) {
            delete window._isDiagramMode;
          }
          // 将文档类型存储到localStorage，以便文档页面获取
          localStorage.setItem('current_document_type', outputType);
          console.log(`【Hero组件】设置文档模式标记，移除图表模式标记，存储文档类型: ${outputType}`);
        }
      }
      
      // 根据输出类型导航
      if (outputType === 'diagram') {
        console.log(`【Hero组件】导航到图表页面: /${username}/${repo}`);
        router.push(`/${username}/${repo}`);
      } else {
        // 如果是任何文档类型，导航到document页面并传递类型参数
        console.log(`【Hero组件】导航到文档页面: /${username}/${repo}/document?type=${outputType}`);
        router.push(`/${username}/${repo}/document?type=${outputType}`);
      }
    }
  };
  
  // 处理输入变化
  const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setRepoInput(value);
    // 调用外部onChange如果存在
    if (onChange) {
      onChange(value);
    }
  };
  
  // 处理点击示例
  const handleExampleClick = (example: { name: string; url: string }) => {
    setRepoInput(example.url);
    if (onChange) {
      onChange(example.url);
    }
    
    const parsedUrl = parseGitHubUrl(example.url);
    if (!parsedUrl) return;
    
    const { username, repo, url } = parsedUrl;
    
    if (onGenerate) {
      onGenerate(url, username, repo);
    } else {
      // 设置全局模式标记，确保使用正确的钩子
      console.log("【Hero组件-示例】准备导航，选择的输出类型:", outputType);
      
      if (typeof window !== 'undefined') {
        if (outputType === 'diagram') {
          // 设置图表模式标记
          window._isDiagramMode = true;
          // 移除文档模式标记（如果有）
          if (window._isDocumentMode) {
            delete window._isDocumentMode;
          }
          console.log("【Hero组件-示例】设置图表模式标记，移除文档模式标记");
        } else {
          // 设置文档模式标记
          window._isDocumentMode = true;
          // 移除图表模式标记（如果有）
          if (window._isDiagramMode) {
            delete window._isDiagramMode;
          }
          // 将文档类型存储到localStorage，以便文档页面获取
          localStorage.setItem('current_document_type', outputType);
          console.log(`【Hero组件-示例】设置文档模式标记，移除图表模式标记，存储文档类型: ${outputType}`);
        }
      }
      
      // 根据输出类型导航
      if (outputType === 'diagram') {
        console.log(`【Hero组件-示例】导航到图表页面: /${username}/${repo}`);
        router.push(`/${username}/${repo}`);
      } else {
        // 如果是任何文档类型，导航到document页面并传递类型参数
        console.log(`【Hero组件-示例】导航到文档页面: /${username}/${repo}/document?type=${outputType}`);
        router.push(`/${username}/${repo}/document?type=${outputType}`);
      }
    }
  };
  
  return (
    <div className="flex flex-col items-center w-full max-w-4xl mx-auto">
      <div className="relative mx-auto flex w-full flex-col items-start justify-center sm:flex-row sm:items-center">
        {/* 左侧星星SVG - 使用动态类名根据中英文不同调整位置 */}
        {/* 类名说明:
          - h-auto w-16: 设置星星初始大小
          - flex-shrink-0: 防止星星被压缩
          - -translate-x-10 translate-y-4: 在移动设备上的初始位置偏移
          - p-2: 内边距
          - animate-float: 应用浮动动画效果
          - sm:absolute: 小屏幕以上使用绝对定位
          - sm:w-20: 小屏幕以上的宽度
          - sm:-translate-y-16: 向上偏移
          - isChinese判断: 中文界面时使用不同的水平偏移以避免与文字重叠
          - md:relative: 中等屏幕恢复相对定位
          - lg:absolute: 大屏幕重新使用绝对定位
          - lg:-translate-x-full: 大屏幕向左完全偏移
        */}
        <svg
          className={`left-0 h-auto w-16 flex-shrink-0 -translate-x-10 translate-y-4 p-2 animate-float sm:absolute sm:w-20 sm:-translate-y-16 ${
            isChinese 
              ? "sm:-translate-x-40 md:-translate-x-24 lg:-translate-y-20" 
              : "sm:-translate-x-36 md:-translate-x-20 lg:-translate-y-16"
          } md:relative md:w-24 md:-translate-y-0 lg:absolute lg:ml-32 lg:-translate-x-full lg:-ml-16`}
          viewBox="0 0 91 98"
          fill="none"
          xmlns="http://www.w3.org/2000/svg"
        >
          {/* 星星主体形状 - 使用路径绘制不规则的星形 */}
          <path
            d="m35.878 14.162 1.333-5.369 1.933 5.183c4.47 11.982 14.036 21.085 25.828 24.467l5.42 1.555-5.209 2.16c-11.332 4.697-19.806 14.826-22.888 27.237l-1.333 5.369-1.933-5.183C34.56 57.599 24.993 48.496 13.201 45.114l-5.42-1.555 5.21-2.16c11.331-4.697 19.805-14.826 22.887-27.237Z"
            fill="url(#starGrad1)" /* 使用渐变填充 */
            stroke="#000" /* 黑色描边 */
            strokeWidth="3.445" /* 描边宽度 */
            className="dark:stroke-white" /* 暗模式下切换为白色描边 */
          />
          {/* 渐变定义 - 从浅蓝色到深蓝色的线性渐变 */}
          <defs>
            <linearGradient id="starGrad1" x1="0%" y1="0%" x2="100%" y2="100%">
              <stop offset="0%" stopColor="#3b82f6" /> {/* 起始颜色 - 蓝色 */}
              <stop offset="100%" stopColor="#2563eb" /> {/* 结束颜色 - 深蓝色 */}
            </linearGradient>
          </defs>
          {/* 装饰性线条 - 为星星添加放射状的装饰线 */}
          <path
            d="M79.653 5.729c-2.436 5.323-9.515 15.25-18.341 12.374m9.197 16.336c2.6-5.851 10.008-16.834 18.842-13.956m-9.738-15.07c-.374 3.787 1.076 12.078 9.869 14.943M70.61 34.6c.503-4.21-.69-13.346-9.49-16.214M14.922 65.967c1.338 5.677 6.372 16.756 15.808 15.659M18.21 95.832c-1.392-6.226-6.54-18.404-15.984-17.305m12.85-12.892c-.41 3.771-3.576 11.588-12.968 12.681M18.025 96c.367-4.21 3.453-12.905 12.854-14"
            stroke="#000" /* 黑色描边 */
            strokeWidth="2.548" /* 描边宽度 */
            strokeLinecap="round" /* 圆形线帽，使线条末端更圆润 */
            className="dark:stroke-white" /* 暗模式下切换为白色描边 */
          />
        </svg>
        <h1 className={`relative z-10 inline-block w-full text-center font-bold tracking-tighter ${
          isChinese 
            ? 'mx-auto max-w-[90%] px-8 text-5xl sm:text-5xl md:text-6xl lg:pt-5 lg:text-7xl' 
            : 'mx-auto max-w-[95%] text-4xl sm:text-4xl md:text-5xl lg:pt-5 lg:text-6xl'
        }`}>
          <span className={`bg-gradient-to-r from-black to-gray-700 bg-clip-text text-transparent dark:from-white dark:to-gray-300 ${
            isChinese ? 'px-4 py-1' : ''
          }`}>
            {t("heroTitle")}
          </span>
        </h1>
        
        {/* 右侧星星SVG - 使用动态类名根据中英文不同调整位置 */}
        {/* 类名说明:
          - bottom-0 right-0: 基础定位在右下角
          - hidden: 在移动设备上隐藏
          - h-auto w-16: 设置星星初始大小
          - flex-shrink-0: 防止星星被压缩
          - -translate-x-0 translate-y-10: 默认偏移
          - animate-float-delay: 应用延迟浮动动画
          - md:block: 中等屏幕以上显示
          - md:translate-y-20: 向下偏移
          - lg:absolute: 大屏幕使用绝对定位
          - lg:w-20: 大屏幕上的大小
          - isChinese判断: 中文界面使用更大的偏移确保不重叠
        */}
        <svg
          className={`bottom-0 right-0 hidden h-auto w-16 flex-shrink-0 -translate-x-0 translate-y-10 animate-float-delay md:block md:translate-y-20 lg:absolute lg:w-20 ${
            isChinese 
              ? "lg:-translate-x-64 lg:translate-y-28 lg:mr-4" 
              : "lg:-translate-x-60 lg:translate-y-24 lg:mr-2"
          }`}
          viewBox="0 0 92 80"
          fill="none"
          xmlns="http://www.w3.org/2000/svg"
        >
          {/* 星星主体形状 - 使用路径绘制第二个不规则星形 */}
          <path
            d="m35.213 16.953.595-5.261 2.644 4.587a35.056 35.056 0 0 0 26.432 17.33l5.261.594-4.587 2.644A35.056 35.056 0 0 0 48.23 63.28l-.595 5.26-2.644-4.587a35.056 35.056 0 0 0-26.432-17.328l-5.261-.595 4.587-2.644a35.056 35.056 0 0 0 17.329-26.433Z"
            fill="url(#starGrad2)" /* 使用较浅的蓝色渐变填充 */
            stroke="#000" /* An initial black stroke */
            strokeWidth="2.868" /* 比左侧星星略薄的描边 */
            className="dark:stroke-white" /* 暗模式下切换为白色描边 */
          />
          {/* 渐变定义 - 从更浅的蓝色到较浅的蓝色 */}
          <defs>
            <linearGradient id="starGrad2" x1="0%" y1="0%" x2="100%" y2="100%">
              <stop offset="0%" stopColor="#60a5fa" /> {/* 起始颜色 - 浅蓝色 */}
              <stop offset="100%" stopColor="#3b82f6" /> {/* 结束颜色 - 蓝色 */}
            </linearGradient>
          </defs>
          {/* 装饰性线条 - 为右侧星星添加不同形状的放射状装饰线 */}
          <path
            d="M75.062 40.108c1.07 5.255 1.072 16.52-7.472 19.54m7.422-19.682c1.836 2.965 7.643 8.14 16.187 5.121-8.544 3.02-8.207 15.23-6.971 20.957-1.97-3.343-8.044-9.274-16.588-6.254M12.054 28.012c1.34-5.22 6.126-15.4 14.554-14.369M12.035 28.162c-.274-3.487-2.93-10.719-11.358-11.75C9.104 17.443 14.013 6.262 15.414.542c.226 3.888 2.784 11.92 11.212 12.95"
            stroke="#000" /* 黑色描边 */
            strokeWidth="2.319" /* 比左侧星星装饰线更细的线条 */
            strokeLinecap="round" /* 圆形线帽 */
            className="dark:stroke-white" /* 暗模式下切换为白色描边 */
          />
        </svg>
      </div>
      
      {/* 仓库输入和生成按钮 */}
      <p className="mx-auto my-4 max-w-2xl text-center text-xl text-gray-700 dark:text-gray-300">
        {t("heroSubtitle")}
      </p>
      
      <form onSubmit={handleGenerate} className="w-full max-w-xl mt-8">
        <div className="flex w-full flex-col gap-4 sm:flex-row sm:items-stretch">
          <input
            type="text"
            value={repoInput}
            onChange={handleInputChange}
            placeholder={t("repoUrlPlaceholder")}
            className="w-full rounded-lg border-[3px] border-black/75 bg-white/80 px-4 py-4 text-base font-medium shadow-[4px_4px_0_0_rgba(0,0,0,0.7)] backdrop-blur-sm transition-all duration-300 hover:shadow-[2px_2px_0_0_rgba(0,0,0,0.7)] placeholder:text-base placeholder:font-normal placeholder:text-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 dark:border-white/20 dark:bg-gray-800/80 dark:text-white dark:shadow-[4px_4px_0_0_rgba(200,200,200,0.2)] dark:hover:shadow-[2px_2px_0_0_rgba(200,200,200,0.2)] dark:placeholder:text-gray-400 dark:focus:ring-blue-400"
          />
          <Button
            type="submit"
            className={`h-auto flex items-center justify-center rounded-lg border-[3px] border-black/75 bg-gradient-to-br from-blue-500 to-blue-600 font-medium text-white shadow-[4px_4px_0_0_rgba(0,0,0,0.7)] transition-all duration-300 hover:-translate-x-0.5 hover:-translate-y-0.5 hover:shadow-[2px_2px_0_0_rgba(0,0,0,0.7)] dark:border-white/20 dark:from-blue-600 dark:to-blue-700 dark:shadow-[4px_4px_0_0_rgba(200,200,200,0.2)] dark:hover:shadow-[2px_2px_0_0_rgba(200,200,200,0.2)] ${
              isChinese 
                ? 'sm:w-32 px-6 py-4 text-lg' 
                : 'min-w-fit px-4 py-4'
            }`}
          >
            {t("generateButton")}
          </Button>
        </div>
        
        {/* 输出类型选择器 */}
        <div className="mt-6 flex justify-center">
          <OutputTypeSelector 
            value={outputType} 
            onChange={handleOutputTypeChange}
          />
        </div>
      </form>
      
      {/* 示例仓库 */}
      <div className="mt-12 w-full max-w-xl">
        <h3 className="text-lg font-medium text-gray-800 dark:text-gray-200">{t("examplesTitle")}</h3>
        <div className="mt-4 grid grid-cols-1 gap-3 sm:grid-cols-2">
          {examples.map((example, index) => (
            <button
              key={index}
              onClick={() => handleExampleClick(example)}
              className="group overflow-hidden rounded-lg border-[3px] border-black/75 bg-white/90 p-4 text-left text-black shadow-[4px_4px_0_0_rgba(0,0,0,0.7)] backdrop-blur-sm transition-all duration-300 hover:-translate-x-0.5 hover:-translate-y-0.5 hover:bg-gray-50/90 hover:shadow-[2px_2px_0_0_rgba(0,0,0,0.7)] dark:border-white/20 dark:bg-gray-800/80 dark:text-white dark:shadow-[4px_4px_0_0_rgba(200,200,200,0.2)] dark:hover:bg-gray-700/80 dark:hover:shadow-[2px_2px_0_0_rgba(200,200,200,0.2)]"
            >
              <span className="relative inline-block">
                {example.name}
                <span className="absolute bottom-0 left-0 h-0.5 w-0 bg-gradient-to-r from-blue-500 to-blue-600 transition-all duration-300 group-hover:w-full dark:from-blue-600 dark:to-blue-400"></span>
              </span>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
};

export default Hero;
